package com.bankcomm.util;

import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.specialwidget.DigitPasswordKeyPad;
import com.rytong.tools.clienthello.ClientHello;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.crypto.Base64;
import com.rytong.tools.crypto.HMac;
import com.rytong.tools.httpconnect.HttpManager;
import com.rytong.tools.httpconnect.WaitDialog.Task;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

/**
 * SecretUtil.java
 * 
 * @author cheng.l 2013-5-16 下午02:45:23
 */
public class SecretUtil {
	private String serverRandom ;
	private String srk;
	private String KeyValue;
	String radomNum = null;
	
	public String getRadomNum() {
		return radomNum;
	}
	
	public void setRadomNum(String radomNum) {
		this.radomNum = radomNum;
	}

	/**
	 * 一次一密方法
	 * 
	 * @param value
	 * @param task
	 * @return
	 * */
	public static String encryptValue(String value,Task task){
		
		String content = value;
		try{
		if (value == null ) {
			return value;
		}
		byte[] cUnixTime = Utils.getClientGMTUnixTime();
		byte[] clientRandom = ClientHello.getClientRandom(28);
		byte[] RNC = new byte[32];
		System.arraycopy(cUnixTime, 0, RNC, 0, cUnixTime.length);
		System.arraycopy(clientRandom, 0, RNC, cUnixTime.length, clientRandom.length);
		String rncStr = Base64.encode(RNC);
		HttpManager hm = LPMid.getInstance().hm_;
		String body = "clientrandom=" + Utils.escapeURIComponent(rncStr);
		body = AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);
		String status = (String) hm.sendPostRequest(ConfigManager.SERVER_URI + ConfigManager.GET_ONESERCRET, body, task, null, null);
//		if (status == null)
//			throw new NullPointerException(Constant.ERR_ENCRYPT_SERVER_01);
//		if (status.indexOf("<error") != -1) {
//			String error = Utils.getXMLResponseAttribute(status, "string=\"", 0, Utils.MATCH);
//			throw new Exception(error);
//		}
		status = AESCipher.decrypt(status, AESCipher.serverKey_, AESCipher.serverIv_);
		String serverRandom = Utils.getXMLResponseAttribute(status, "serverrandom=\"", 0, Utils.MATCH);
		byte[] RNS = Base64.decodeToBytes(serverRandom);
		byte[] seed = new byte[RNC.length + RNS.length];
		System.arraycopy(RNC, 0, seed, 0, RNC.length);
		System.arraycopy(RNS, 0, seed, RNC.length, RNS.length);
		byte[] secret = HMac.PRF(ClientHello.PMS_, HMac.TLS_ONCE_SECRET_CONST(), seed, 48);
		byte[] key = ClientHello.getAESKey(secret);
		byte[] iv = ClientHello.getAESIv(secret);
		byte[] data = AESCipher.encrypt(content.getBytes("UTF-8"), key, iv);
		content = Base64.encode(data);			
		}catch (Exception e) {
		}
		return content;
	}

	public void OnCreateInputWindow(Activity activity_, EditText edit, Dialog dlg) {
		if(LPMid.getInstance().num==null){
			LPToastUtil.getInstance().getToast(activity_.getString(R.string.notice_retry), activity_);
			return;
		}
		DigitPasswordKeyPad dpk = new DigitPasswordKeyPad(activity_, edit);
		View pswView = dpk.setup();
		dlg = new Dialog(activity_, R.style.popupAnimation);
		dlg.setContentView(pswView,new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		dpk.dlg_ = dlg;

		// 点击dialog以外的区域关闭dialog
		dlg.setCanceledOnTouchOutside(true);
		dlg.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface arg0) {
				LPMid.getInstance().isShow=false;
			}
		});

		dlg.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface arg0) {
				LPMid.getInstance().isShow=false;
			}
		});

		//设置dialog位置
		Window mWindow = dlg.getWindow();
		mWindow.setWindowAnimations(R.style.popupAnimation);
		mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		// 使对话框位于屏幕的底部并居中
		mWindow.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
		// 使对话框二边没有空隙
		mWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		if (!dlg.isShowing()) {
			dlg.show();
		}
	}

	public void getRadomKey(LPMid mid) {
		String str = null;
		byte[] key = null ;
		byte[] iv = null ;
		try {
			if(LPMid.digitStr != null){
				str = LPMid.digitStr ;
				return ;
			}else{
				try{
				getServerRandom(mid); // 发请求
				}catch(Exception e){
					mid.notShowDialog=true;
					return;
				}
				byte[] rns3 = Base64.decodeToBytes(serverRandom);
				byte[] rnc3 = Base64.decodeToBytes(this.getRadomNum());
				byte[] ms3;
				ms3 = getMS3(rnc3, rns3);
				key = ClientHello.getAESKey(ms3);
				iv = ClientHello.getAESIv(ms3);
				str = AESCipher.decrypt(KeyValue, key, iv).trim();
				//一个页面多个密码键盘时，做一次键值对请求
				LPMid.digitStr = str ;
			}
			Utils.printOutToConsole("对应关系："+str);
		String[] allPairArr = str.split("\\|");
		if (allPairArr != null && allPairArr.length > 0) {
			int allPairLen = allPairArr.length;
			mid.num = new String[allPairLen];
			mid.letter = new String[allPairLen];
			for (int i = 0; i < allPairLen; i++) {
				String[] onePairArr = allPairArr[i].split(":");
				mid.num[i] = onePairArr[0];
				mid.letter[i] = onePairArr[1];
			}
		}
		}catch (Exception e) {
			mid.notShowDialog=true;
		}
	}

	// 获取服务端随机数
	public void getServerRandom(LPMid mid) throws Exception {

		// 计算客户端随机数
		byte[] clientGmtUnixTime = getClientGMTUnixTime();
		byte[] clientRandom = ClientHello.getClientRandom(28);
		this.setRadomNum(Base64.encode(Utils.jogBytes(clientGmtUnixTime, clientRandom)));
		// 获取服务端随机数
		String clientBody = "RNC=".concat(Utils.escapeURIComponent(this.getRadomNum()));
		clientBody = AESCipher.encrypt(clientBody, AESCipher.clientKey_, AESCipher.clientIv_);
	    try{
		srk = ((String) mid.hm_.sendPostRequest(ConfigManager.SERVER_URI + ConfigManager.GET_RANDOM_KEY_BOARD_SERVERKEY, clientBody, null, null,
				null)).trim();
	    }catch (Exception e){
	    	//if(act instanceof BaseView){
	    	//	((BaseView)act).handleException(srk);
	    	//}
	    }
		srk = (AESCipher.decrypt(srk, AESCipher.serverKey_, AESCipher.serverIv_)).trim();
		radomjsonParser(srk);
	}

	private byte[] getClientGMTUnixTime() {
		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		int hours = date.getHours();
		byte[] clientGmtUnixTime = new byte[4];
		clientGmtUnixTime[0] = (byte) ((hours & 0x0000FF00) >> 8);
		clientGmtUnixTime[1] = (byte) ((hours & 0x000000FF));
		int minutes = date.getMinutes();
		clientGmtUnixTime[2] = (byte) ((minutes & 0x0000FF00) >> 8);
		clientGmtUnixTime[3] = (byte) ((minutes & 0x000000FF));
		return clientGmtUnixTime;
	}
	
	private byte[] getMS3(byte[] rnc3, byte[] rns3) throws Exception {
		byte[] ms3RncRnsSeed = Utils.jogBytes(rnc3, rns3);
		byte[] ms3 = createMS3(ClientHello.PMS_, ms3RncRnsSeed);
		return ms3;
	}
	private final byte[] createMS3(byte[] pms3, byte[] ms3RncRnsSeed) throws Exception {
		byte[] ms3Label = HMac.TLS_ONCE_SECRET_CONST();
		byte[] ms3 = createMasterSecret(pms3, ms3Label, ms3RncRnsSeed, 48);
		return ms3;
	}
	
	private final byte[] createMasterSecret(byte[] tokenPassword, byte[] label, byte[] seed, int len) throws Exception {
		byte[] ms = HMac.PRF(tokenPassword, label, seed, len);
		return ms;
	}
	//处理json
	private void radomjsonParser(String srk2) throws Exception {
		// TODO Auto-generated method stub
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(srk2);
			serverRandom= jsonObject.getString("RNS");
			KeyValue= jsonObject.getString("dynImageKeyModule");
		} catch (JSONException e) {
			
		}
	}
}
